<?php
namespace api\modules\v1\models;

use api\common\models\Common;
use api\func\func;
use Yii;
use yii\helpers\Url;
use yii\web\HttpException;
use api\common\models\User;

/**
 * Login form
 */
class Simlogin extends User
{

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username', 'required','message'=>'{attribute}不能为空', 'on' => ['lr_login']],
            ['username', 'filter', 'filter' => 'trim', 'on' => ['lr_login']],
            [['username'],'match','pattern'=>'/^[a-zA-z0-9]{4,20}$/','message'=>'{attribute}必须为4-20位字母数字或组合', 'on' => ['lr_login']],


            ['phone', 'required', 'on' => ['lr_login']],
            ['phone','match','pattern'=>'/^1[34578]{1}\d{9}$/','message'=>'请输入正确的手机号', 'on' => ['lr_login']],
            ['code', 'required', 'on' => ['lr_login']],
            ['code', 'integer', 'on' => ['lr_login']],
            [['code'], 'filter', 'filter' => 'trim', 'on' => ['lr_login']],
            [['code'], 'validateCode', 'on' => ['lr_login']],

            //第三方登录验证
            ['type', 'in', 'range' => ['qq','wx','wb'], 'on' => ['lr_login']],
            ['type', 'validateType', 'on' => ['lr_login']],
            ['openid', 'safe', 'on' => ['lr_login']],

            //昵称 头像
            ['nickname', 'validateNickName', 'on' => ['lr_login']],
            ['head_img', 'url', 'on' => ['lr_login']],
        ];
    }

    public function attributeLabels()
    {
        return [
            'username' => Yii::t('app', '账号'),
            'phone' => Yii::t('app', '手机号码'),
            'code' => Yii::t('app', '短信验证码'),
            'type' => Yii::t('app', '第三方登录类型'),
            'openid' => Yii::t('app', '第三方登录验证字符串'),
            'nickname' => Yii::t('app', '昵称'),
            'head_img' => Yii::t('app', '头像'),
        ];
    }

    public function validateType($attribute, $params){
        $openid_field = $this->type.'_openid';
        $this->$openid_field = $this->openid;
    }

    public function validateNickName($attribute, $params){
        if(isset($this->nickname)){
            $this->nickname = strip_tags($this->nickname);
        }
        return true;
    }


    /*
     * 简化采集和登录步骤
     * @return bool|null|static
     */
    public function lr(){
        if ($this->validate()) {
            if(!$userinfo = self::find()->where('(`username` = "'.$this->username.'" or `phone` = "'.$this->username.'") and status = '.self::STATUS_ACTIVE)->asArray()->one()){       //不存在账号
                if($this->type !='' && $this->openid != ''){ //判断该Openid 是否已经存在绑定其他账号
                    $openid_field = $this->type.'_openid';
                    if(self::findOne([$openid_field=>$this->openid])){
                        throw new HttpException(401,'该'.Common::formatType($this->type).'已绑定其他账号',0);
                    }
                }

                $this->status = self::STATUS_ACTIVE;
                $this->created_at = date('Y-m-d H:i:s',time());
                $this->updated_at = date('Y-m-d H:i:s',time());
                $this->access_token = $this->makeAccessToken($this->phone,'');
                $userinfo = $this->getAttributes();
                $this->save(false);
                $insert_id = Yii::$app->db->lastInsertID;

                $message = '尊敬的注册用户您好，您已经成功注册‘中国文化云’帐号，感谢您对‘中国文化云’的关注与支持。';
                $msg = new Msg();
                $msg->take_uid = $insert_id;
                $msg->send_uid = 0;
                $msg->message = $message;
                $msg->type = 99;
                $msg->url = Url::to(['msg/list','type' => 99], false);
                $msg->time = date('Y-m-d H:i:s');
                $msg->isread = 0;
                $msg->insert();

                Code::alidayuReg($this->phone);
            }else{ //已存在账号
                if($this->type !='' && $this->openid != ''){ //如果进行第三方绑定
                    $openid_field = $this->type.'_openid';
                    $openid_data = $userinfo[$openid_field]; //表中openid

                    if($openid_data != '' && $openid_data != $this->$openid_field){ //已存在绑定 且 openid不一致
                        throw new HttpException(401,'该账号'.Common::formatType($this->type).'绑定已经存在',0);
                    }elseif($openid_data == ''){ //openid为空 进行第三方绑定

                        if(self::find()->where("$openid_field='".$this->openid."' and phone !='".$this->phone."'")->one()){ //判断该Openid 是否已经存在绑定其他账号
                            throw new HttpException(401,'该'.$this->type.'已绑定其他账号',0);
                        }

                        $update_data =[];
                        $update_data[$openid_field] = $this->$openid_field;

                        if(isset($this->nickname) && $this->nickname != '' && $userinfo['nickname'] ==''){
                            $update_data['nickname'] = $this->nickname;
                            $userinfo['nickname'] = $this->nickname;
                        }
                        if(isset($this->head_img) && $this->head_img != '' && $userinfo['head_img'] ==''){
                            $update_data['head_img'] = $this->head_img;
                            $userinfo['head_img'] = $this->head_img;
                        }

                        self::updateAll($update_data,['id'=>$userinfo['id']]);
                        $userinfo[$openid_field] = $this->$openid_field;
                    }else{ //已经绑定了 且openid一致
                        $update_data =[];
                        if(isset($this->nickname) && $this->nickname != '' && $userinfo['nickname'] ==''){
                            $update_data['nickname'] = $this->nickname;
                            $userinfo['nickname'] = $this->nickname;
                        }
                        if(isset($this->head_img) && $this->head_img != '' && $userinfo['head_img'] ==''){
                            $update_data['head_img'] = $this->head_img;
                            $userinfo['head_img'] = $this->head_img;
                        }
                        if(count($update_data) >0 ){
                            self::updateAll($update_data,['id'=>$userinfo['id']]);
                        }
                    }
                }
            }
            $userinfo['has_pwd'] = 0;
            if($userinfo['password_hash'] != ''){
                $userinfo['has_pwd'] = 1;
            }
            unset($userinfo['auth_key']);
            unset($userinfo['password_hash']);
            unset($userinfo['password_reset_token']);
            unset($userinfo['email']);
            unset($userinfo['collect_category']);
            return $userinfo;
        }
        return null;
    }

    /*
     * 生成加密字符串
     * @param $username
     * @param $password
     * @return string
     */
    public function makeAccessToken($username,$password){
        return md5($username.Yii::$app->params['access_token_seeds'].$password);
    }

}
